using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NFreeMarker.Core
{
    /// <summary>
    /// A instruction that handles if-elseif-else blocks.
    /// </summary>
    internal sealed class IfBlock : TemplateElement
    {
        internal IfBlock(ConditionalBlock block)
        {
            NestedElements = new List<TemplateElement>();
            AddBlock(block);
        }

        internal void AddBlock(ConditionalBlock block)
        {
            NestedElements.Add(block);
        }

        internal override void Accept(Environment env)
        {
            ConditionalBlock block = NestedElements
                .Cast<ConditionalBlock>()
                .FirstOrDefault(cblock => cblock.Condition == null || cblock.Condition.IsTrue(env));

            if (block != null && block.NestedBlock != null)
            {
                env.Visit(block.NestedBlock);
            }
        }

        public override string GetCanonicalForm()
        {
            var buf = new StringBuilder();
            foreach (ConditionalBlock cblock in NestedElements)
            {
                buf.Append(cblock.GetCanonicalForm());
            }
            buf.Append("</#if>");
            return buf.ToString();
        }

        internal override TemplateElement PostParseCleanup(bool stripWhitespace)
        {
            if (NestedElements.Count == 1)
            {
                var cblock = (ConditionalBlock) NestedElements[0];
                cblock.IsSimple = true;
                cblock.SetLocation(GetTemplate(), cblock, this);
                return cblock.PostParseCleanup(stripWhitespace);
            }
            return base.PostParseCleanup(stripWhitespace);
        }

        public override string GetDescription()
        {
            return "if-else ";
        }
    }
}